﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using MyLib;

namespace Billing2.cls
{
    public partial class ClsImportSubscriber
    {
        public List<Organization> organizations = new List<Organization>();
        public MyList<Subscriber, string> subscribers = new MyList<Subscriber, string>();
        public int error = 0;
        public string Message = "";
        public ClsChangeRequestHelper.ChangeRequestType ChangeRequestType;
        public bool autoCreateOrgSiteCC = false;

        public ClsImportSubscriber(ClsChangeRequestHelper.ChangeRequestType _ChangeRequestType)
        {
            this.ChangeRequestType = _ChangeRequestType;
        }

        ~ClsImportSubscriber()
        {
        }

        //lbl_organization.Text = String.Format("New organization ({0})", dgv.Rows.Count);       
        //lbl_subscriber.Text = String.Format("New subscriber ({0})", dgv.Rows.Count);

        public void Preview(string filename, string ConnectionString, DateTime default_start_date)
        {
            CleanLog();
            error = 0;
            bool do_not_check_duplicate_in_DB = false;
            FileStream fs = null;
            StreamReader sr = null;
            DBCommands2 db = null;
            try
            {
                if (filename.ToLower().RightStr(4) != ".csv")
                    throw new Exception("only CSV file allowed");
                fs = new FileStream(filename, FileMode.Open);
                sr = new StreamReader(fs);

                db = new DBCommands2(ConnectionString);
                db.BeginTransaction();

                int row = 0;
                ValidFile(sr, ref row);

                int approximate_total_lines = (int)(fs.Length / 100);
                OnProcess(0);
                while (true)
                {
                    OnProcess(Convert.ToInt32(row * 100.0 / approximate_total_lines));

                    Subscriber data = null;
                    int col = 1;
                    try
                    {
                        data = ReadSubscriber(sr, ref col);
                        if (data == null) //end of file
                            break;
                    }
                    catch (Exception ex)
                    {
                        error++;
                        //throw new Exception(string.Format("Cell[{0}{1}]: {2}", Index2ColumnName(n), i, ex.Message));
                        Log("Line[{0},{1}]: {2}", row, Index2ColumnName(col), ex.Message);
                    }

                    try
                    {
                        if (data != null) //if read subscriber ok
                        {
                            PreviewOrganization(data, db, do_not_check_duplicate_in_DB);
                            PreviewSubscriber(data, default_start_date, db, do_not_check_duplicate_in_DB);
                        }
                    }
                    catch (Exception ex)
                    {
                        error++;
                        //throw new Exception(string.Format("Line[{0}]: {1}", i, ex.Message));
                        Log("Line[{0}]: {1}", row, ex.Message);
                    }

                    row++;
                }
                db.Rollback();

                OnProcess(100);
                Log("Preview finished. new organization={0} new site={1} new cc={2} new subscriber={3} error={4}",
                    Organization.OrgCount(organizations),
                    Organization.SiteCount(organizations),
                    Organization.CCCount(organizations),
                    subscribers.Count,
                    error);
            }
            finally
            {
                if (sr != null)
                    sr = null;
                if (fs != null)
                {
                    fs.Close();
                    fs = null;
                }
            }

            //MyExcel excel = null;
            //try
            //{
            //    stop = false;

            //    organizations.Clear();
            //    subscribers.Clear();
            //    ClearResult();
            //    Application.DoEvents();

            //    if (Properties.Settings.Default.ConnectionString == "")
            //        throw new Exception("please setup database connection string first!");
            //    if (!File.Exists(tb_file.Text))
            //        throw new Exception("file does not exist");
            //    string filename = tb_file.Text;
            //    Log.Write("Process file '{0}'", filename);
            //    Properties.Settings.Default.LastFilename = filename;
            //    Properties.Settings.Default.Save();

            //    DBCommands db = new DBCommands(Properties.Settings.Default.ConnectionString);
            //    db.ExceptionMode = true;

            //    int start_row = 3;
            //    excel = new MyExcel(filename, SheetName);
            //    ValidExcelFile(excel, ref start_row);

            //    int error = 0;
            //    OnProcess(0);
            //    for (int i = start_row; i <= excel.max_rows; i++)
            //    {
            //        OnProcess(Convert.ToInt32(i * 100.0 / excel.max_rows));
            //        Application.DoEvents();
            //        if (stop)
            //            throw new Exception("cancelled by user!");

            //        Subscriber data = null;
            //        int n = 1;
            //        try
            //        {
            //            data = ReadSubscriber(excel, i, ref n);
            //            if (data == null) //end of file
            //                break;
            //        }
            //        catch (Exception ex)
            //        {
            //            error++;
            //            //throw new Exception(string.Format("Cell[{0}{1}]: {2}", Index2ColumnName(n), i, ex.Message));
            //            Log.Write(Color.Red, "Cell[{0}{1}]: {2}", Index2ColumnName(n), i, ex.Message);
            //        }

            //        try
            //        {
            //            if (data != null) //if read subscriber ok
            //            {
            //                ValidSubscriber(data, default_start_date);
            //                ProcessOrganization(data, db, do_not_check_duplicate_in_DB);
            //                ProcessSubscriber(data, db, do_not_check_duplicate_in_DB);
            //            }
            //        }
            //        catch (Exception ex)
            //        {
            //            error++;
            //            //throw new Exception(string.Format("Line[{0}]: {1}", i, ex.Message));
            //            Log.Write(Color.Red, "Line[{0}]: {1}", i, ex.Message);
            //        }
            //    }
            //    OnProcess(100);
            //    Log.Write(error == 0 ? Color.Blue : Color.Red, "Preview finished. new organization={0} new subscriber={1} error={2}", dgv_organization.Rows.Count, dgv_subscriber.Rows.Count, error);
            //    this.btn_preview.Enabled = true;
            //    this.btn_import.Enabled = error == 0;
            //    this.btn_stop.Enabled = false;
            //}
            //catch (Exception ex)
            //{
            //    this.btn_preview.Enabled = true;
            //    this.btn_import.Enabled = false;
            //    this.btn_stop.Enabled = false;

            //    Log.Write(Color.Red, ex.Message);
            //    MessageBox.Show(ex.Message);
            //}
            //finally
            //{
            //    if (excel != null)
            //    {
            //        excel.Close();
            //        excel = null;
            //    }
            //}
        }

        public void Submit(string ConnectionString, bool create_cr_record)
        {
            CleanLog();
            DBCommands2 db = null;
            try
            {
                db = new DBCommands2(ConnectionString);
                db.BeginTransaction();

                if (autoCreateOrgSiteCC)
                {
                    for (int i = 0; i < this.organizations.Count; i++)
                        ImportOrganization(this.organizations[i], db);
                }
                foreach (Subscriber subscriber in this.subscribers)
                {
                    //if (create_cr_record)
                        CreateChangeRequest(subscriber, db);
                    //ImportSubscriber(this.subscribers[i], db);
                }
                db.Commit();

                Log("Import finished. organization={0} site={1} cc={2} subscriber={3}",
                    Organization.OrgCount(organizations),
                    Organization.SiteCount(organizations),
                    Organization.CCCount(organizations),
                    subscribers.Count);
            }
            finally
            {
                if (db != null && db.InTransaction)
                    db.Rollback();
            }
        }

        void OnProcess(int n)
        {
        }
    }
}